package com.zhangxiaofanfan.hotcode.first;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode080 {
    public static void main(String[] args) {
        HotCode080 hotCode = new HotCode080();
        String s = "eccbbbbdec";
        System.out.println(hotCode.partitionLabels(s));
    }

    public List<Integer> partitionLabels(String s) {
        Map<Character, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            map.computeIfAbsent(s.charAt(i), ArrayList::new).add(i);
        }
        List<int[]> range = new ArrayList<>();
        List<Integer> result = new ArrayList<>();
        map.forEach((key, value) -> range.add(new int[]{value.getFirst(), value.getLast()}));
        range.sort(Comparator.comparingInt(o -> o[0]));
        int left = range.getFirst()[0], right = range.getFirst()[1];
        for (int i = 1; i < range.size(); i++) {
            if (right < range.get(i)[0]) {
                result.add(right - left + 1);
                left = range.get(i)[0];
                right = range.get(i)[1];
            } else {
                right = Math.max(right, range.get(i)[1]);
            }
        }
        result.add(right - left + 1);
        return result;
    }

}
